<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/5 0005
 * Time: 下午 3:27
 */
namespace app\admin\controller;

use app\admin\model\StoreAuthGroup;
use think\Request;

class Srole extends Base {
    public function _initialize()
    {
        parent::_initialize();
        $this->model = 'store_auth_group';
        $defaultWhere = $this->getDefaultWhere();
        $this->defaultWhere = $defaultWhere;
    }

    public function index()
    {
        $request = $this->request;
        $param = $request->param();
        // Reset filter
        if ($request->param('reset')) {
            return redirect(fullUrl($request->path()));
        }
        if($request->isAjax()){
            $model = model($this->model);

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'] + 1;
            // 排序条件
            $order = '';

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                $where = array_merge($this->defaultWhere, $where);
            }
            if($this->defaultOrder){
                $order = $this->defaultOrder;
            }
            $data = $model->where($where)->limit($start,$length)->order($order)->select();
            if($data){
                foreach ($data as &$v){
                    $rolelist = explode(',',$v['rules']);
                    $role = db('store_auth_rule')->where('id','in',$rolelist)->field('title')->select();
                    $rolenames = '';
                    if($role){
                        $i=0;
                        foreach ($role as $val){
                            if($i==0){
                                $rolenames .= $val['title'];
                            }else{
                                $rolenames .= '，'.$val['title'];
                            }
                            $i++;
                        }
                    }
                    $v['rulesname'] = $rolenames;
                }
            }
            $count = $model->where($where)->count();
            $result = [
                'code' => '0',
                'msg' => '请求成功',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->fetch('list');

    }
    public function add(Request $request)
    {
        return parent::add($request);
    }

    public function addpost(Request $request,$ad=''){
        $param = $request->param();
        if(!empty($param['role_name']) && !empty($param['rolelist'])){
            if(is_array($param['rolelist'])){
                $temp = '';
                foreach ($param['rolelist'] as $v){
                    $parentids = $this->getparent($v);
                    $temp .= $parentids;
                }
                $uniparentids = array_unique(array_filter(explode(',',$temp)));
                $rolelist = implode(',',array_merge($uniparentids,$param['rolelist']));
                if(!empty($param['id'])){
                    $model = StoreAuthGroup::where('id',$param['id'])->find();
                }else{
                    $model = new StoreAuthGroup();
                }
                $model->title = $param['role_name'];
                $model->rules = $rolelist;
                $model->save();
                return $this->success('ok');

            }else{
                return $this->error('权限列表参数异常');
            }

        }else{
            return $this->error('参数错误');
        }
    }

    public function edit(Request $request){
        $param = $request->param();
        if(!empty($param['id'])){
            $store_auth_group = db('store_auth_group')->where('id',$param['id'])->find();
            if($store_auth_group){
                return $this->fetch('',[
                    'info' => $store_auth_group
                ]);
            }else{
                return $this->error('数据异常');
            }
        }else{
            return $this->error('参数错误');
        }

    }

    private function getparent($id){
        $pids = '';
        $parent_id = db('store_auth_rule')->where('id',$id)->value('parent_id');
        if($parent_id != 0){
            $pids .= $parent_id;
            $npids = $this->getparent($parent_id);
            if(isset($npids)){
                $pids .= ','.$npids;
            }
        }
        return $pids;
    }

    public function getrole(Request $request){
        $param = $request->param();
        $groupid = 0;
        if(isset($param['id'])){
            $groupid = $param['id'];
        }
        $field = 'id as value,title,parent_id';
        $rule = db('store_auth_rule')->where('status',1)->field($field)->select();
        $rolearr = [];
        if($groupid != 0){
            $group = db('store_auth_group')->where('id',$groupid)->field('rules')->find();
            if($group){
                $rolearr = explode(',',$group['rules']);
            }
        }
        $list = $this->getTree($rule, $rolearr);
        return json_encode($this->Treetoarray($list));
    }

    private function Treetoarray($list){
        $temp = [];
        foreach ($list as $k=>$v){
            if($v['data']){
                $ch = [];
                foreach ($v['data'] as $val){
                    array_push($ch,$val);
                }
                $v['data'] = $ch;
                $this->Treetoarray($v['data']);
            }
            array_push($temp,$v);
        }
        return $temp;
    }

    public function getTree($array, $rolearr, $pid =0){
        //声明静态数组,避免递归调用时,多次声明导致数组覆盖
        $list = [];
        foreach ($array as $key => $value){
            if(in_array($value['value'],$rolearr)){
                $value['checked'] = true;
            }
            //第一次遍历,找到父节点为根节点的节点 也就是pid=0的节点
            if ($value['parent_id'] == $pid){
                //把数组放到list中
                $list[$key] = $value;
                //把这个节点从数组中移除,减少后续递归消耗
                unset($array[$key]);
                //开始递归,查找父ID为该节点ID的节点,级别则为原级别+1
                $list[$key]['data'] = $this->getTree($array, $rolearr, $value['value']);
            }
        }
        return $list;
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model('store_auth_group');
        if ($request->isPost()) {
            $data = $request->param();
            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }


}